﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using HCDV.HCSP;

namespace HCDV
{
    public class HCRainEF
    {
        #region  触发型工作流引擎处理(应该单独到后台引擎-)
        /// <summary>
        /// 处理发起 hcrain_wf
        /// cUid业务创建人ID，sUid业务提交人ID
        /// </summary>
        public void hcrain_wf_start(string cUid,string sUid)
        {
            try
            {
                //日后，要封装批处理
                using (dbsimple db = new dbsimple())
                {
                    #region**************业务的发起处理---------------------
                    //查找待发起的业务
                    DataTable dt_tostart = db.Query(@"select t.id,t.fruntype,t.frunywid,
hcr_w_next.fnextid,hcr_w_next.fdeid,hcr_w_wtoyw.ywmaintable
from hcr_w_runuser   t
left join 
 hcr_w_wtoyw on t.fruntype=hcr_w_wtoyw.ywcode  
left join 
 hcr_w_next on hcr_w_wtoyw.wdeid=hcr_w_next.fdeid and hcr_w_next.fntype='发起'
  where fruningdo='待处理' and fhcrdostate='发起'");
                    foreach (DataRow dr in dt_tostart.Rows)
                    {
                        //分析是否存在--避免重复发起
                        DataTable dt_run = db.Query(string.Format("select id from hcr_w_run where fruntype='{0}' and frunywid='{1}'", dr["fruntype"].ToString(), dr["frunywid"].ToString()));
                        if (dt_run == null || dt_run.Rows.Count == 0)
                        {
                            //查找下一步状态
                            DataTable dt_runnext = db.Query("select * from hcr_w_next where id=" + dr["fnextid"].ToString());
                            if (dt_runnext != null && dt_runnext.Rows.Count > 0)
                            {
                                DataRow dr_run = dt_runnext.Rows[0];
                                //插入下一步实例  
                                db.SpExe(string.Format("insert into hcr_w_run(fruntype,frunywid,fdeid,fnid,fnname,fntype,faddtime,fstates,fsetuptime,fywstate,fywcreuid,fywsubuid)values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')"
                                    , dr["fruntype"].ToString()//业务代码
                                    , dr["frunywid"].ToString()//业务ID
                                    , dr_run["fdeid"].ToString()//流程ID
                                    , dr_run["id"].ToString()//当前流程步骤ID
                                    , dr_run["fnname"].ToString()//当前流程步骤名称
                                    , dr_run["fntype"].ToString()//当前流程步骤类型
                                    , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")//发起时间
                                    , "待处理"//业务状态
                                    , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")//最后时间
                                    , dr_run["fstatefyw"].ToString()//业务数据状态
                                    ,cUid//创建人
                                    ,sUid//提交人
                                    ));
                                //更新本状态
                                db.SpExe("update hcr_w_runuser set fruningdo='已处理' where id=" + dr["id"].ToString());
                                //更新主业务表的状态字段
                                db.SpExe(string.Format("update {0} set fhcrwdeywstates='{1}' where id={2}", dr["ywmaintable"].ToString(), dr_run["fstatefyw"].ToString(), dr["frunywid"].ToString()));

                            }
                            else
                            {
                                db.SpExe("update hcr_w_runuser set fruningdo='已处理-没有下一步' where id=" + dr["id"].ToString());
                                continue;
                            }


                        }
                        else
                        {

                            db.SpExe("update hcr_w_runuser set fruningdo='已处理-重复发起' where id=" + dr["id"].ToString());
                            continue;
                        }


                    }



                    #endregion
                    //业务的提交处理---------------------



                    //DataTable ddd = db.Query("select * from mrbaseinf");
                    //DataSet dddd = db.getProc("getUserInfo", allinfo);
                }
                hcrain_wf_auto();
            }
            catch (Exception ee)
            { LogHelper.LogError("hcrain_wf_start", ee); }
        }
        /// <summary>
        /// 处理流程流转 hcrain_wf
        /// </summary>
        public void hcrain_wf_next()
        {
            try
            {
                //日后，要封装批处理
                using (dbsimple db = new dbsimple())
                {
                    #region**************业务的待处理处理---------------------
                    //查找待处理的业务
                    DataTable dt_hasdo = db.Query(@"select t.id,t.fruntype,t.frunywid,t.fhcrdostate,t.fdoend
,hcr_w_wtoyw.ywmaintable
 FROM hcr_w_runuser t left join 
 hcr_w_wtoyw on t.fruntype=hcr_w_wtoyw.ywcode       where t.fruningdo='待处理' and t.fhcrdostate<>'发起'");
                    foreach (DataRow dr in dt_hasdo.Rows)
                    {
                        //查找运行的实例
                        DataTable dt_run = db.Query(string.Format("select * from hcr_w_run where fruntype='{0}' and frunywid='{1}'", dr["fruntype"].ToString(), dr["frunywid"].ToString()));
                        if (dt_run != null && dt_run.Rows.Count > 0)
                        {
                            DataTable dt_runnext;
                            //查找当前实例步骤信息
                            DataTable dt_runnow = db.Query("select * from hcr_w_next where id=" + dt_run.Rows[0]["fnid"].ToString());
                            if (dr["fdoend"].ToString() == "通过")
                            {
                                //查找下一步状态
                                dt_runnext = db.Query("select * from hcr_w_next where id=" + dt_runnow.Rows[0]["fnextid"].ToString());
                                DataRow dr_run = dt_runnext.Rows[0];
                                //更新实例
                                db.SpExe(string.Format("update    hcr_w_run set fnid='{0}',fnname='{1}',fntype='{2}',fstates='{3}',fsetuptime='{4}',fywstate='{5}',fiscallback='' where id={6}"
                                    , dr_run["id"].ToString()//当前流程步骤ID
                                    , dr_run["fnname"].ToString()//当前流程步骤名称
                                    , dr_run["fntype"].ToString()//当前流程步骤类型
                                    , ((dr_run["fnname"].ToString() == "结束") ? "已结束" : "待处理")//业务状态
                                    , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")//最后时间
                                     , dr_run["fstatefyw"].ToString()//业务数据状态
                                     , dt_run.Rows[0]["id"].ToString()
                                    ));
                                //更新本状态
                                db.SpExe("update hcr_w_runuser set fruningdo='已处理' where id=" + dr["id"].ToString());
                                //更新主业务表的状态字段
                                db.SpExe(string.Format("update {0} set fhcrwdeywstates='{1}' where id={2}", dr["ywmaintable"].ToString(), dr_run["fstatefyw"].ToString(), dr["frunywid"].ToString()));
                            }
                            else
                            {
                                //查找上一步状态
                                string thisnextid = dt_run.Rows[0]["fnid"].ToString();
                                while (true)
                                {
                                    dt_runnext = db.Query("select * from hcr_w_next where fnextid='" + thisnextid + "'");
                                    if (dt_runnext == null || dt_runnext.Rows.Count == 0)
                                    {
                                        dt_runnext = db.Query("select * from hcr_w_next where fnextid like '%''" + thisnextid + "''%'");
                                        if (!dt_runnext.Rows[0]["fntype"].ToString().Equals("条件分支"))
                                        {
                                            break;
                                        }
                                        else
                                        {
                                            thisnextid = dt_runnext.Rows[0]["id"].ToString();
                                        }
                                    }
                                    else if (!dt_runnext.Rows[0]["fntype"].ToString().Equals("条件分支"))
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        thisnextid = dt_runnext.Rows[0]["id"].ToString();
                                    }
                                }
                                DataRow dr_run = dt_runnext.Rows[0];
                                if (dr_run["fntype"].Equals("发起"))
                                {
                                    //删除实例
                                    db.SpExe("delete  from hcr_w_run where  id=" + dt_run.Rows[0]["id"].ToString());
                                }
                                else
                                {
                                    //更新实例
                                    db.SpExe(string.Format("update    hcr_w_run set fnid='{0}',fnname='{1}',fntype='{2}',fstates='{3}',fsetuptime='{4}',fywstate='{5}',fiscallback='退回' where id={6}"
                                        , dr_run["id"].ToString()//当前流程步骤ID
                                        , dr_run["fnname"].ToString()//当前流程步骤名称
                                        , dr_run["fntype"].ToString()//当前流程步骤类型
                                        , "待处理"//业务状态
                                        , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")//最后时间
                                         , dr_run["fstatefyw"].ToString()//业务数据状态
                                         , dt_run.Rows[0]["id"].ToString()
                                        ));
                                }
                                //更新本状态
                                db.SpExe("update hcr_w_runuser set fruningdo='已处理' where id=" + dr["id"].ToString());
                                //更新主业务表的状态字段
                                db.SpExe(string.Format("update {0} set fhcrwdeywstates='{1}' where id={2}", dr["ywmaintable"].ToString(), dr_run["fstatefyw"].ToString(), dr["frunywid"].ToString()));
                            }
                        }
                        else
                        {
                            db.SpExe("update hcr_w_runuser set fruningdo='已处理-业务没发起' where id=" + dr["id"].ToString());
                            continue;
                        }

                    }



                    #endregion

                }
                hcrain_wf_auto();
            }
            catch (Exception ee)
            { LogHelper.LogError("hcrain_wf_next", ee); }
        }

        //string re = new Stringexe().hcvlForString("#if($age >18) 大于是18 #else  小于18 #end", new string[] {"age" }, new object[] { 15});
        public void hcrain_wf_auto()
        {
            try
            {
                using (dbsimple db = new dbsimple())
                {
                    #region
                    //查找待处理分支的业务
                    DataTable dt_hasdo = db.Query(@"select *,hcr_w_wtoyw.ywmaintable  from view_hc_wfruning  t left join 
 hcr_w_wtoyw on t.fruntype=hcr_w_wtoyw.ywcode    where t.hcrntype='条件分支'");
                    foreach (DataRow dr in dt_hasdo.Rows)
                    {
                        //

                        //查找运行的实例
                        DataTable dt_run = db.Query(string.Format("select * from hcr_w_run where fruntype='{0}' and frunywid='{1}'", dr["fruntype"].ToString(), dr["frunywid"].ToString()));
                        if (dt_run != null && dt_run.Rows.Count > 0)
                        {
                            DataTable dt_runnext;
                            if (true)
                            {

                                //获取下一步ID
                                string nextid = "";
                                string[] fn;
                                string[] fv;
                                {
                                    string hcrnautofiles = dr["hcrnautofiles"].ToString();//getmoney:yw_fremoney#getminmoney:yw_fminmoney
                                    string hcrntypeauto = dr["hcrntypeauto"].ToString();
                                    string[] hcrnautofiles_arry = hcrnautofiles.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                                    //取出业务表数据
                                    DataTable dt_wyinfo =
                                        db.Query(string.Format("select * from {0} where id ='{1}'", dr["ywmaintable"].ToString(), dr["frunywid"].ToString()));
                                    fn = new string[hcrnautofiles_arry.Length];
                                    fv = new string[hcrnautofiles_arry.Length];
                                    for (int aras = 0; aras < hcrnautofiles_arry.Length; aras++)
                                    {
                                        fn[aras] = hcrnautofiles_arry[aras].Split(':')[0];
                                        fv[aras] = dt_wyinfo.Rows[0][hcrnautofiles_arry[aras].Split(':')[1].Replace("yw_", "")].ToString();
                                    }

                                    nextid = new HCDV.HCString.Stringexe().hcvlForString(hcrntypeauto, fn, fv);
                                }
                                nextid = nextid.Trim();
                                //查找下一步状态
                                dt_runnext = db.Query("select * from hcr_w_next where id=" + nextid);
                                DataRow dr_run = dt_runnext.Rows[0];
                                //更新实例
                                db.SpExe(string.Format("update    hcr_w_run set fnid='{0}',fnname='{1}',fntype='{2}',fstates='{3}',fsetuptime='{4}',fywstate='{5}',fiscallback='' where id={6}"
                                    , dr_run["id"].ToString()//当前流程步骤ID
                                    , dr_run["fnname"].ToString()//当前流程步骤名称
                                    , dr_run["fntype"].ToString()//当前流程步骤类型
                                    , "待处理"//业务状态
                                    , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")//最后时间
                                     , dr_run["fstatefyw"].ToString()//业务数据状态
                                     , dt_run.Rows[0]["id"].ToString()
                                    ));

                                //更新主业务表的状态字段
                                db.SpExe(string.Format("update {0} set fhcrwdeywstates='{1}' where id={2}", dr["ywmaintable"].ToString(), dr_run["fstatefyw"].ToString(), dr["frunywid"].ToString()));
                            }
                        }


                    }



                    #endregion

                }
            }
            catch (Exception ee)
            { LogHelper.LogError("hcrain_wf_auto", ee); }
        }
        #endregion
    }
}
